from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework import viewsets, status
from rest_framework.views import APIView

from oAuth.models import NewUser, Informations, Tasks, Shortages, Machines
from rest_framework.response import Response
from oAuth.serializers import UserSerializer, Informationerializer, Taskerializer, ShortageSerializer
from oAuth.serializers import MachineSerializer
from django.db.models import Q
from rest_framework.pagination import PageNumberPagination
from rest_framework import filters
from django.http import HttpResponse,JsonResponse


# Create your views here.
#分页
class NewPageNumberPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 50

class UserInfoViewSet(viewsets.ViewSet):
    queryset = NewUser.objects.all().order_by('-date_joined')
    http_method_names = ['get']

    def list(self, request, *args, **kwargs):
        print('ok')
        user_info = NewUser.objects.filter(id=request.user.id).values()[0]
        role = request.user.roles
        if role == 0:
            user_info['roles'] = ['admin']
        else:
            user_info['roles'] = ['user']

        return Response(user_info)
    def perform_destroy(self, instance):
        instance.save()




    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        instance.is_delete = True
        print('ok')
        instance.save()

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

class InformationViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(~Q(is_delete=True))
    serializer_class = Informationerializer
    pagination_class = NewPageNumberPagination
    filter_backends = [filters.SearchFilter]
    search_fields = ['number', 'shortage', 'person_record', 'person_responsibility']

    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def perform_destroy(self, instance):
        instance.is_delete = True
        instance.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class RecoverInformationViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(Q(is_delete=True))
    serializer_class = Informationerializer
    pagination_class = NewPageNumberPagination
    filter_backends = [filters.SearchFilter]
    search_fields = ['number', 'shortage', 'person_record', 'person_responsibility']



class TaskViewSet2(viewsets.ModelViewSet):
    queryset = Tasks.objects.all().filter(is_fix=True)
    serializer_class = Taskerializer
    pagination_class = NewPageNumberPagination
    filter_backends = [filters.SearchFilter]
    search_fields = [ 'number', 'person_record', 'person_finish']
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Tasks.objects.all().filter(~Q(is_fix=True))
    serializer_class = Taskerializer
    pagination_class = NewPageNumberPagination
    filter_backends = [filters.SearchFilter]
    search_fields = [ 'number', 'person_record', 'person_finish']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

class UserViewSet(viewsets.ModelViewSet):
    queryset = NewUser.objects.all()
    serializer_class = UserSerializer
    pagination_class = NewPageNumberPagination
    filter_backends = [filters.SearchFilter]
    search_fields = ['username', 'name', 'roles']
    # list :get
    # create: post
    # put: update(整体更新，提供所有更改后的字段信息)
    # patch：partial_update(据不更新，仅提供需要修改的信息)
    # delete: destroy
    # get_id: retrieve

    def list(self, request, *args, **kwargs):
        user = request.user
        # if 'roles' in user and user.roles == 1:
        #         self.queryset = self.queryset.filter(~Q(username='admin'))
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        self.perform_create(serializer)
        user = NewUser.objects.get(username=request.data['username'])
        user.set_password(request.data['password'])
        user.save()

        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)



class ShortageViewSet(viewsets.ModelViewSet):
    queryset = Shortages.objects.all()
    serializer_class = ShortageSerializer
    pagination_class = NewPageNumberPagination
    filter_backends = [filters.SearchFilter]
    search_fields = ['shortage']

class MachineViewSet(viewsets.ModelViewSet):
    queryset = Machines.objects.all()
    serializer_class = MachineSerializer
    pagination_class = NewPageNumberPagination
    filter_backends = [filters.SearchFilter]
    search_fields = ['machine']

@csrf_exempt
def Evaluate_first(request):
    data_dic = dict(request.POST)
    data = []
    for i in data_dic:
        if data_dic[i][0] == '':
            return JsonResponse({'error_message':'error', 'data':'输入有空值，请更改'})
        else:
            data.append(eval(data_dic[i][0]))
    if data[-1] == 30:
        return JsonResponse({'error_message': 'success', 'data': 0.97})
    else:
        return JsonResponse({'error_message': 'success', 'data': 0.80})


@csrf_exempt
def Evaluate_second(request):
    data_dic = dict(request.POST)
    data = []
    for i in data_dic:
        if data_dic[i][0] == '':
            return JsonResponse({'error_message': 'error', 'data': '输入有空值，请更改'})
        else:
            data.append(eval(data_dic[i][0]))
    if data[-1] == 30:
        return JsonResponse({'error_message': 'success', 'data': 0.97})
    else:
        return JsonResponse({'error_message': 'success', 'data': 0.80})








#得到所有数据----导入数据库用的
# class getAllViewSet(viewsets.ModelViewSet):
#     queryset = Informations.objects.all()
#     serializer_class = Informationerializer
#     pagination_class = NewPageNumberPagination
#     filter_backends = [filters.SearchFilter]
#     search_fields = ['shortage', 'person_record', 'person_responsibility']
#
#     def list(self, request, *args, **kwargs):
#         queryset = self.filter_queryset(self.get_queryset())
#         print(123)
#         w = open('C:\\Users\\Jason\\Desktop\\Project\\djangoTest2-main\\oAuth\\1.txt', encoding='utf-8')
#         st = w.readlines()
#         dic = {
#             'count': len(st),
#             'data':[]
#         }
#         ls = []
#         for i in range(len(st)):
#             s = st[i]
#             s.strip('\n')
#             t = s.split(';')
#             k = {
#                 'number': t[0],
#                 'shortage': t[1],
#                 'detail': t[2],
#                 'occuer_time': t[3],
#                 'cause': t[4],
#                 'option': t[5],
#                 'person_responsibility': t[6],
#                 'person_record': t[6],
#                 'condition': t[-2],
#                 'record_time': t[3],
#             }
#             dic['data'].append(k)
#
#         serializer = self.get_serializer(queryset, many=True)
#         return Response(dic)

class DeleteInformationViewSet(viewsets.ModelViewSet):
    queryset = Informations.objects.all().filter(is_delete=True)
    serializer_class = Informationerializer
    pagination_class = NewPageNumberPagination
    filter_backends = [filters.SearchFilter]
    search_fields = ['number', 'shortage', 'person_record', 'person_responsibility']

    def list(self, request, *args, **kwargs):

        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)


        serializer = self.get_serializer(queryset, many=True)

        return Response(serializer.data)